import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isEmpty from "lodash/isEmpty";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _dec11, _dec12, _dec13, _dec14, _class, _class2;

/**
 * Config - 系统配置
 * @date: 2018-10-24

 * @version: 1.0.0

 */
import React, { Component } from 'react';
import { connect } from 'dva';
import { Form, Spin, Tabs, Icon } from 'antd';
import { Bind } from 'lodash-decorators';
import { Content, Header } from 'components/Page';
import { Button as ButtonPermission } from 'components/Permission';
import notification from 'utils/notification';
import intl from 'utils/intl';
import formatterCollections from 'utils/intl/formatterCollections';
import { VERSION_IS_OP } from 'utils/config';
import { getCurrentOrganizationId, isTenantRoleLevel } from 'utils/utils';
import System from "./System.js";
import Iam from "./Iam.js";
import Oauth from "./Oauth.js";
import styles from "./index.less?modules";
var ConfigDetail = (_dec = connect(function (_ref) {
  var config = _ref.config,
      loading = _ref.loading,
      user = _ref.user,
      global = _ref.global;
  return {
    user: user,
    global: global,
    config: config,
    isSite: !isTenantRoleLevel(),
    queryTenantConfigLoading: loading.effects['config/queryTenantConfig'],
    queryOrganizationConfigLoading: loading.effects['config/queryOrganizationConfig'],
    updateTenantConfigLoading: loading.effects['config/updateTenantConfig'],
    updateOrganizationConfigLoading: loading.effects['config/updateOrganizationConfig'],
    organizationId: getCurrentOrganizationId()
  };
}), _dec2 = Form.create({
  fieldNameProp: null
}), _dec3 = formatterCollections({
  code: ['cpfm.config']
}), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec10 = Bind(), _dec11 = Bind(), _dec12 = Bind(), _dec13 = Bind(), _dec14 = Bind(), _dec(_class = _dec2(_class = _dec3(_class = (_class2 = /*#__PURE__*/function (_Component) {
  _inherits(ConfigDetail, _Component);

  var _super = _createSuper(ConfigDetail);

  function ConfigDetail(props) {
    var _this;

    _classCallCheck(this, ConfigDetail);

    _this = _super.call(this, props);
    _this.systemRef = React.createRef();
    _this.iamRef = React.createRef();
    _this.oauthRef = React.createRef();
    _this.state = {
      activeKey: 'system'
    };
    return _this;
  }

  _createClass(ConfigDetail, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          config = _this$props.config,
          match = _this$props.match,
          queryTenantConfigLoading = _this$props.queryTenantConfigLoading,
          queryOrganizationConfigLoading = _this$props.queryOrganizationConfigLoading,
          updateTenantConfigLoading = _this$props.updateTenantConfigLoading,
          updateOrganizationConfigLoading = _this$props.updateOrganizationConfigLoading,
          isSite = _this$props.isSite,
          _this$props$global$su = _this$props.global.supportLanguage,
          languageList = _this$props$global$su === void 0 ? [] : _this$props$global$su;
      var _this$state$activeKey = this.state.activeKey,
          activeKey = _this$state$activeKey === void 0 ? 'system' : _this$state$activeKey;
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Header, {
        title: intl.get('cpfm.config.view.message.title').d('系统配置')
      }, /*#__PURE__*/React.createElement(ButtonPermission, {
        icon: "save",
        type: "primary",
        permissionList: [{
          code: "".concat(match.path, ".button.save"),
          type: 'button',
          meaning: '系统配置-保存'
        }],
        onClick: this.handleSave,
        loading: isSite ? updateTenantConfigLoading : updateOrganizationConfigLoading,
        disabled: isSite ? queryTenantConfigLoading : queryOrganizationConfigLoading
      }, intl.get('cpaas.common.button.save').d('保存'))), /*#__PURE__*/React.createElement(Content, {
        className: styles['config-content']
      }, /*#__PURE__*/React.createElement(Spin, {
        spinning: isSite ? queryTenantConfigLoading : queryOrganizationConfigLoading
      }, /*#__PURE__*/React.createElement(Tabs, {
        activeKey: activeKey,
        onChange: this.handleChange,
        animated: false,
        tabPosition: "left" // className={styles['cpfm-config-tabs']}

      }, /*#__PURE__*/React.createElement(Tabs.TabPane, {
        tab: /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
          className: styles['config-content-tab-system']
        }, /*#__PURE__*/React.createElement(Icon, {
          className: styles['config-content-tab-system-icon']
        }), /*#__PURE__*/React.createElement("span", null, intl.get('cpfm.config.view.title.system').d('基础数据配置')))),
        key: "system"
      }, /*#__PURE__*/React.createElement(System, {
        config: config,
        wrappedComponentRef: this.systemRef
      })), /*#__PURE__*/React.createElement(Tabs.TabPane, {
        tab: /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
          className: styles['config-content-tab-iam']
        }, /*#__PURE__*/React.createElement(Icon, {
          className: styles['config-content-tab-iam-icon']
        }), /*#__PURE__*/React.createElement("span", null, intl.get('cpfm.config.view.title.iam').d('用户中心配置')))),
        key: "iam"
      }, /*#__PURE__*/React.createElement(Iam, {
        config: config,
        wrappedComponentRef: this.iamRef,
        isSite: isSite || VERSION_IS_OP
      })), (isSite || VERSION_IS_OP) && /*#__PURE__*/React.createElement(Tabs.TabPane, {
        tab: /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
          className: styles['config-content-tab-iam']
        }, /*#__PURE__*/React.createElement(Icon, {
          className: styles['config-content-tab-oauth-icon']
        }), /*#__PURE__*/React.createElement("span", null, intl.get('cpfm.config.view.title.oauth').d('登录首页配置')))),
        key: "oauth"
      }, /*#__PURE__*/React.createElement(Oauth, {
        config: config,
        wrappedComponentRef: this.oauthRef,
        languageList: languageList
      }))))));
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      this.queryConfig();
      this.init();
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.props.dispatch({
        type: 'config/updateState',
        payload: {
          data: []
        }
      });
    }
    /**
     * 查询系统配置信息
     */

  }, {
    key: "queryConfig",
    value: function queryConfig() {
      var _this$props2 = this.props,
          dispatch = _this$props2.dispatch,
          organizationId = _this$props2.organizationId,
          isSite = _this$props2.isSite;
      dispatch({
        type: isSite ? 'config/queryTenantConfig' : 'config/queryOrganizationConfig',
        payload: organizationId
      });
    }
  }, {
    key: "handleChange",
    value: function handleChange(value) {
      this.setState({
        activeKey: value
      });
    }
  }, {
    key: "handleSave",
    value: function handleSave() {
      var _this2 = this;

      var _this$props3 = this.props,
          dispatch = _this$props3.dispatch,
          organizationId = _this$props3.organizationId,
          isSite = _this$props3.isSite;
      var activeKey = this.state.activeKey;
      var fieldValues = [];
      var errorFlag = false;

      if (this.systemRef.current && activeKey === 'system') {
        this.systemRef.current.props.form.validateFields(function (err, fieldsValue) {
          if (!err) {
            fieldValues = fieldsValue;
          } else {
            errorFlag = true;
          }
        });
      }

      if (this.iamRef.current && activeKey === 'iam') {
        this.iamRef.current.props.form.validateFields(function (err, fieldsValue) {
          if (!err) {
            fieldValues = _objectSpread(_objectSpread({}, fieldValues), fieldsValue);
          } else {
            errorFlag = true;
          }
        });
      }

      if (this.oauthRef.current && activeKey === 'oauth') {
        this.oauthRef.current.props.form.validateFields(function (err, fieldsValue) {
          if (!err) {
            fieldValues = _objectSpread(_objectSpread({}, fieldValues), fieldsValue);
          } else {
            errorFlag = true;
          }
        });
      }

      var values = this.updateData(fieldValues);

      if (!errorFlag) {
        dispatch({
          type: isSite ? 'config/updateTenantConfig' : 'config/updateOrganizationConfig',
          payload: {
            values: values,
            organizationId: organizationId
          }
        }).then(function (res) {
          if (res) {
            if (_this2.systemRef.current) {
              _this2.systemRef.current.props.form.resetFields();
            }

            if (_this2.iamRef.current) {
              _this2.iamRef.current.props.form.resetFields();
            }

            if (_this2.oauthRef.current) {
              _this2.oauthRef.current.props.form.resetFields();
            }

            notification.success();

            _this2.queryConfig();

            if (res.length > 0 && activeKey === 'system') {
              var title = _objectSpread({}, res.filter(function (item) {
                return item.configCode === 'TITLE';
              })[0]);

              var logo = _objectSpread({}, res.filter(function (item) {
                return item.configCode === 'LOGO';
              })[0]);

              var favicon = _objectSpread({}, res.filter(function (item) {
                return item.configCode === 'FAVICON';
              })[0]); // const menuLayout = res.filter(item => item.configCode === 'MENU_LAYOUT');


              var menuLayoutTheme = _objectSpread({}, res.filter(function (item) {
                return item.configCode === 'MENU_LAYOUT_THEME';
              })[0]);

              var roleMergeFlag = _objectSpread({}, res.filter(function (item) {
                return item.configCode === 'ROLE_MERGE';
              })[0]);

              dispatch({
                type: 'user/updateCurrentUser',
                payload: {
                  title: title.configValue,
                  logo: logo.configValue,
                  favicon: favicon.configValue,
                  // menuLayout: newMenuLayout.configValue,
                  menuLayoutTheme: menuLayoutTheme.configValue,
                  roleMergeFlag: roleMergeFlag.configValue
                }
              });
            }
          }
        });
      }
    }
  }, {
    key: "updateData",
    value: function updateData(obj) {
      var _this3 = this;

      var _this$props4 = this.props,
          _this$props4$config$d = _this$props4.config.data,
          data = _this$props4$config$d === void 0 ? [] : _this$props4$config$d,
          organizationId = _this$props4.organizationId;
      var values = [];

      if (!_isEmpty(obj)) {
        Object.keys(obj).forEach(function (item) {
          switch (item) {
            case 'title':
              values.push(_objectSpread(_objectSpread({
                category: 'system',
                configCode: 'TITLE',
                tenantId: organizationId
              }, _this3.findConfig('TITLE', data)), {}, {
                configValue: obj.title
              }));
              break;

            case 'logo':
              values.push(_objectSpread(_objectSpread({
                category: 'system',
                configCode: 'LOGO',
                tenantId: organizationId
              }, _this3.findConfig('LOGO', data)), {}, {
                configValue: obj.logo
              }));
              break;

            case 'favicon':
              values.push(_objectSpread(_objectSpread({
                category: 'system',
                configCode: 'FAVICON',
                tenantId: organizationId
              }, _this3.findConfig('FAVICON', data)), {}, {
                configValue: obj.favicon
              }));
              break;

            case 'menuLayout':
              values.push(_objectSpread(_objectSpread({
                category: 'system',
                configCode: 'MENU_LAYOUT',
                tenantId: organizationId
              }, _this3.findConfig('MENU_LAYOUT', data)), {}, {
                configValue: obj.menuLayout
              }));
              break;

            case 'menuLayoutTheme':
              values.push(_objectSpread(_objectSpread({
                category: 'system',
                configCode: 'MENU_LAYOUT_THEME',
                tenantId: organizationId
              }, _this3.findConfig('MENU_LAYOUT_THEME', data)), {}, {
                configValue: obj.menuLayoutTheme
              }));
              break;

            case 'roleMergeFlag':
              values.push(_objectSpread(_objectSpread({
                category: 'system',
                configCode: 'ROLE_MERGE',
                tenantId: organizationId
              }, _this3.findConfig('ROLE_MERGE', data)), {}, {
                configValue: obj.roleMergeFlag
              }));
              break;

            case 'password':
              values.push(_objectSpread(_objectSpread({
                category: 'iam',
                configCode: 'CIAM.IF_SEND_MODIFY_PASSWORD',
                tenantId: organizationId
              }, _this3.findConfig('CIAM.IF_SEND_MODIFY_PASSWORD', data)), {}, {
                configValue: obj.password
              }));
              break;

            case 'sendFlag':
              values.push(_objectSpread(_objectSpread({
                category: 'iam',
                configCode: 'CIAM.IF_SEND_CREATE_USER',
                tenantId: organizationId
              }, _this3.findConfig('CIAM.IF_SEND_CREATE_USER', data)), {}, {
                configValue: obj.sendFlag
              }));
              break;

            case 'url':
              values.push(_objectSpread(_objectSpread({
                category: 'iam',
                configCode: 'CIAM.INDEX_URL',
                tenantId: organizationId
              }, _this3.findConfig('CIAM.INDEX_URL', data)), {}, {
                configValue: obj.url
              }));
              break;

            case 'loginTitle':
              values.push(_objectSpread(_objectSpread({
                category: 'oauth',
                configCode: 'COTH.TITLE',
                tenantId: organizationId
              }, _this3.findConfig('COTH.TITLE', data)), {}, {
                configValue: obj.loginTitle
              }));
              break;

            case 'copyright':
              values.push(_objectSpread(_objectSpread({
                category: 'oauth',
                configCode: 'COTH.COPYRIGHT',
                tenantId: organizationId
              }, _this3.findConfig('COTH.COPYRIGHT', data)), {}, {
                configValue: obj.copyright
              }));
              break;

            case 'loginLogo':
              values.push(_objectSpread(_objectSpread({
                category: 'oauth',
                configCode: 'COTH.LOGO_URL',
                tenantId: organizationId
              }, _this3.findConfig('COTH.LOGO_URL', data)), {}, {
                configValue: obj.loginLogo
              }));
              break;

            case 'languageFlag':
              values.push(_objectSpread(_objectSpread({
                category: 'oauth',
                configCode: 'COTH.SHOW_LANGUAGE',
                tenantId: organizationId
              }, _this3.findConfig('COTH.SHOW_LANGUAGE', data)), {}, {
                configValue: 0
              }));
              break;

            case 'language':
              values.push(_objectSpread(_objectSpread({
                category: 'oauth',
                configCode: 'COTH.DEFAULT_LANGUAGE',
                tenantId: organizationId
              }, _this3.findConfig('COTH.DEFAULT_LANGUAGE', data)), {}, {
                configValue: 'zh_CN'
              }));
              break;

            default:
              break;
          }
        });
      }

      return values;
    }
  }, {
    key: "updateRestData",
    value: function updateRestData(arr) {
      var _this4 = this;

      var _this$props$config$da = this.props.config.data,
          data = _this$props$config$da === void 0 ? [] : _this$props$config$da;
      var values = [];

      if (data.length > 0) {
        // 复制更新数据
        data.forEach(function (item) {
          if (!_this4.findConfigField(item.configCode, arr)) {
            values.push(item);
          }
        });
      }

      return values;
    }
    /**
     * 从配置列表查找配置项
     * @param {Number|String} field 查询配置字段的 ID 或 Code
     * @param {Array} data 获取到的原配置数组
     */

  }, {
    key: "findConfigField",
    value: function findConfigField(field, data) {
      if (data.length > 0) {
        var dataFilter = data.find(function (item) {
          return item.configCode === field;
        });
        return dataFilter ? dataFilter.configValue : null;
      }
    }
  }, {
    key: "findConfig",
    value: function findConfig(field, data) {
      if (data.length > 0) {
        var dataFilter = data.find(function (item) {
          return item.configCode === field;
        });
        return dataFilter;
      }
    } // 上传图片成功

  }, {
    key: "onUploadSuccess",
    value: function onUploadSuccess(file) {
      var form = this.props.form;

      if (file) {
        form.setFieldsValue({
          logo: file.response
        });
      }
    } // 删除图片成功

  }, {
    key: "onCancelSuccess",
    value: function onCancelSuccess(file) {
      var form = this.props.form;

      if (file) {
        form.setFieldsValue({
          logo: ''
        });
      }
    }
    /**
     * 上传 favicon 成功
     */

  }, {
    key: "handleFaviconUploadSuccess",
    value: function handleFaviconUploadSuccess(file) {
      var form = this.props.form;

      if (file) {
        form.setFieldsValue({
          favicon: file.response
        });
      }
    }
    /**
     * 删除 favicon 成功
     */

  }, {
    key: "handleCancelFaviconUploadSuccess",
    value: function handleCancelFaviconUploadSuccess(file) {
      var form = this.props.form;

      if (file) {
        form.setFieldsValue({
          favicon: ''
        });
      }
    }
    /**
     * 页面初始化， 调用 model 中的初始化 查询值集
     */

  }, {
    key: "init",
    value: function init() {
      var dispatch = this.props.dispatch;
      dispatch({
        type: 'config/init'
      });
    }
  }]);

  return ConfigDetail;
}(Component), (_applyDecoratedDescriptor(_class2.prototype, "queryConfig", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "queryConfig"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleChange", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "handleChange"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleSave", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "handleSave"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "updateData", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "updateData"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "updateRestData", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "updateRestData"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "findConfigField", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "findConfigField"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "findConfig", [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, "findConfig"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onUploadSuccess", [_dec11], Object.getOwnPropertyDescriptor(_class2.prototype, "onUploadSuccess"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onCancelSuccess", [_dec12], Object.getOwnPropertyDescriptor(_class2.prototype, "onCancelSuccess"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleFaviconUploadSuccess", [_dec13], Object.getOwnPropertyDescriptor(_class2.prototype, "handleFaviconUploadSuccess"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleCancelFaviconUploadSuccess", [_dec14], Object.getOwnPropertyDescriptor(_class2.prototype, "handleCancelFaviconUploadSuccess"), _class2.prototype)), _class2)) || _class) || _class) || _class);
export { ConfigDetail as default };